<script>
    import dayjs from "dayjs";

    import { onMount } from "svelte";
    import Formatter from "../utils/Formatter";

    let files = [];

    onMount(async () => {
        console.log(location.pathname);

        files = await (
            await fetch(`/list-files?dir=${location.pathname}`)
        ).json();

        console.log(files);
    });
</script>

<div class="root">
    <div class="container">
        <!-- header -->
        <span class="header name"> Name </span>
        <span class="header"> Last Modified </span>
        <span class="header"> Size </span>

        <!-- parent directory -->
        <a class="name" href={location.pathname.replace(/\/[^/]*\/?$/, "/")}>
            Parent Directory
        </a>

        <!-- libraries -->
        {#each files as o}
            <a class="name" href={o.url}>{o.file}{o.isdir ? "/" : ""}</a>
            <span class="time">
                {dayjs(o.mtime).format("YYYY-MM-DD HH:mm:ss")}
            </span>
            {#if !o.isdir}
                <span class="size">
                    {Formatter.formatSize(o.length)}
                </span>
            {/if}
        {/each}
    </div>
</div>

<style>
    .root {
        height: 100%;
        overflow: auto;
        font-family: cursive;
    }

    .container {
        margin: 1em 2em;
        display: grid;
        grid-row-gap: 5px;
        grid-column-gap: 5px;
        grid-template-columns: auto auto auto;
    }

    .header {
        font-family: "Courier New", Courier, monospace;
        font-weight: bold;
    }

    .name {
        grid-column-start: 1;
    }

    a:hover{
        color: chocolate;
    }

    .time {
        word-break: keep-all;
        white-space: nowrap;
    }
    .size {
        color: red;
    }
</style>
